package com.example.temp;
//import com.huawei.it.apicenter.router.json.JSONObject;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

public class GzipCompressJson {

    public static void main(String[] args) throws ParseException, IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("barCode", "9908227045B2405070AB0057535");
        jsonObject.put("link", "ZSC03W2433100864");
        jsonObject.put("testStartTime", "20240419 10:25:17");
        jsonObject.put("testEndTime", "20240419 10:25:19");
        jsonObject.put("deviceName", "OMM");
        jsonObject.put("factoryName", "浙江公司");
        jsonObject.put("part", "电池盖组件");
        jsonObject.put("projectName", "CYB");
        jsonObject.put("projectStatus", "V4");
        jsonObject.put("objectColor", "黑色");

        String value = compressString(jsonObject.toString());
       // String value = compressString(jsonObject.toJSONString());
        System.out.println(value);
    }

    /**
     * gzip格式压缩json字符串
     *
     * @param jsonString json字符串
     * @return @{@link String}
     */
    public static String compressString(String jsonString) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(jsonString.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        String ret = java.util.Base64.getEncoder().encodeToString(out.toByteArray());
        return ret;
    }
}
